package com.magictower.primary.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kejunzhan
 * @since 2017/12/19
 */

public class AppLockDao {

    public static final String INFO = "info";//表名
    public static final String PACKAGE_NAME = "packagename";//字段：包名

    private final AppLockOpenHelper helper;

    public AppLockDao(Context context) {
        helper = new AppLockOpenHelper(context);
    }

    /**
     * 添加到程序里面
     *
     * @param packageName
     */
    public void add(String packageName) {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(PACKAGE_NAME, packageName);
        db.insert(INFO, null, values);
        db.close();
    }

    public void delete(String packageName) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.delete(INFO, PACKAGE_NAME + "=?", new String[]{packageName});
        db.close();
    }

    public boolean find(String packageName) {
        boolean res = false;
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select count(*) from info where packagename = ?", new String[]{packageName});
        cursor.moveToNext();
        int count = cursor.getInt(0);
        if (count > 0) {
            res = true;
        }
        cursor.close();
        db.close();
        return res;
    }

    public List<String> findAll() {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query(INFO,new String[]{PACKAGE_NAME}, null, null, null, null, null);
        List<String> res = new ArrayList<>();
        while (cursor.moveToNext()) {
            res.add(cursor.getString(0));
        }
        cursor.close();
        db.close();
        return res;
    }
}
